package com.pj.ca.controller;

import com.alibaba.fastjson.JSONObject;
import com.pj.ca.anno.NeedToken;
import com.pj.ca.common.ReturnResult;
import com.pj.ca.common.ReturnResultBuilder;
import com.pj.ca.config.AppConfig;
import com.pj.ca.entity.User;
import com.pj.ca.service.UserService;
import com.pj.ca.util.SimpleTokenManager;
import com.pj.ca.util.Validator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 描述：
 *
 * @author pengjun
 * @date 2021/11/4 10:48
 */
@RestController
@RequestMapping(value = "api")
@NeedToken(isNeed = true)
public class LoginController {

    @Autowired
    SimpleTokenManager tokenManager;
    @Autowired
    AppConfig appConfig;
    @Autowired
    UserService userService;

    /**
     * 登录验证
     *
     * @param param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @NeedToken(isNeed = false)
    public ReturnResult<JSONObject> login(@RequestBody JSONObject param) throws Exception {
        String username = param.getString("username");
        String password = param.getString("password");
        User user = userService.getUserByuserName(username);
        if(null != user) {
            Validator.validator()
                    .isEqueal(user.getUsername(), username, "账户信息不匹配")
                    .isEqueal(user.getPassword(), password, "账户信息不匹配");
        } else {
            Validator.validator()
                    .isEqueal(appConfig.getUsername(), username, "账户信息不匹配")
                    .isEqueal(appConfig.getPassword(), password, "账户信息不匹配");
        }
        String token = tokenManager.createToken(new HashMap<String, String>(), 30L, TimeUnit.MINUTES);
        JSONObject result = new JSONObject();
        result.put("token", token);
        result.put("username", username);
        return ReturnResultBuilder.buildOkResult(result);
    }

}
